package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.List;

import com.sophossystems.client.asmon.dao.TipoRegimenDao;
import com.sophossystems.client.asmon.dto.TipoRegimenDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;


public class TipoRegimenDaoImpl extends AbstractDAO implements TipoRegimenDao {

	private static Logger logger = Logger.getLogger(TipoRegimenDaoImpl.class);
	
	@Override
	public TipoRegimenDTO findByPrimaryKey(final int idRegimen) throws DaoException {
		TipoRegimenDTO regimen = null;
		try {
			regimen = (TipoRegimenDTO) getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
							final Query oQuery = session.createQuery("SELECT r.idRegimen as idRegimen, " +
									"r.descripcion as descripcion FROM " 
									+ getTableName() + " r WHERE r.idRegimen = :id");
							oQuery.setInteger("id", idRegimen);
							TipoRegimenDTO regimenDto = (TipoRegimenDTO) 
									oQuery.setResultTransformer(
									Transformers.aliasToBean(
											TipoRegimenDTO.class)).list().get(0);
							return regimenDto;
							
						}
					});
		} catch (Exception e) {
			logger.error("Error: getRegimen, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getRegimen, cause: "
					+ e.getMessage());
		}
		return regimen;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TipoRegimenDTO> findAll() throws DaoException {
		List<TipoRegimenDTO> regimen = null;
		try {
			regimen = (List<TipoRegimenDTO>) getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
							final Query oQuery = session.createQuery("SELECT r.idRegimen as idRegimen, " +
									"r.descripcion as descripcion FROM " 
									+ getTableName() + " r ORDER BY r.idRegimen");
							List<TipoRegimenDTO> regimenDto = oQuery.setResultTransformer(
									Transformers.aliasToBean(TipoRegimenDTO.class)).list();
							return regimenDto;
						}
					});
		} catch (Exception e) {
			logger.error("Error: getRegimen, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getRegimen, cause: "
					+ e.getMessage());
		}
		return regimen;
	}


	public String getTableName() {
		return "TipoRegimen";
	}
}
